package com.gl.service.impl;

import com.gl.mapper.MeetingMapper;
import com.gl.mapper.MetricsMapper;
import com.gl.mapper.UserMapper;
import com.gl.pojo.entity.Metrics;
import com.gl.pojo.vo.MetricsVo;
import com.gl.service.MetricsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;

@Service
public class MetricsServiceImpl implements MetricsService {

    @Autowired
    private MetricsMapper metricsMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MeetingMapper meetingMapper;


    @Transactional
    @Override
    public MetricsVo getMetricsVo() {
        LocalDate localDate = LocalDate.now();
        Metrics metrics = metricsMapper.getMetrics(localDate);
        MetricsVo metricsVo = new MetricsVo();
        if (metrics != null) {
            // date Todo 之后根据需要改成 task 任务
            if(metricsMapper.getMetricsByDate(localDate) == null) {
                metricsMapper.insert(localDate);
            }
            // newUsersToday
            metricsVo.setNewUsersToday(metrics.getNewUsersToday());
            // online
            metricsVo.setOnline(metrics.getOnline());
            // meetCount
            metricsVo.setMeetingCount(meetingMapper.count());
            // totalUsers
            metricsVo.setTotalUsers(userMapper.count());
            return metricsVo;
        }
        return null;
    }

    /**
     * 新增用户数
     */
    @Override
    @Transactional
    public void insertUser() {
        LocalDate localDate = LocalDate.now();
        if(metricsMapper.getMetricsByDate(localDate) == null) {
            metricsMapper.insert(localDate);
        }
        int affected = metricsMapper.incrementNewUsersToday(localDate, 1);
        if (affected == 0) {
            throw new IllegalStateException("Metrics记录不存在或更新失败");
        }
    }

    /**
     * 在线人数
     */
    @Override
    @Transactional
    public void online() {
        LocalDate localDate = LocalDate.now();
        if(metricsMapper.getMetricsByDate(localDate) == null) {
            metricsMapper.insert(localDate);
        }
        int affected = metricsMapper.incrementOnline(localDate,1);
        if (affected == 0) {
            throw new IllegalStateException("Metrics记录不存在或更新失败");
        }
    }

    /**
     * 下线处理
     */
    @Override
    public void offline() {
        int affected = metricsMapper.incrementOnline(LocalDate.now(),-1);
        if (affected == 0) {
            throw new IllegalStateException("Metrics记录不存在或更新失败");
        }
    }


}
